package cn.com.demo.cert;

import javax.security.auth.x500.X500Principal;
import java.security.cert.CertStore;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;

public class CertStoreExample {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        X509Certificate[] certs = X509CertificateExample.buildCertificateChain();

        //create the store
        CollectionCertStoreParameters params = new CollectionCertStoreParameters(Arrays.asList(certs));
        CertStore store = CertStore.getInstance("Collection", params);

        //create  the selector
        X509CertSelector selector = new X509CertSelector();
        selector.setIssuer(new X500Principal("CN=ROOT").getEncoded());

        //print the subjects of the results
        Iterator i = store.getCertificates(selector).iterator();
        while (i.hasNext()) {
            X509Certificate cert = (X509Certificate) i.next();
            System.out.println(cert.getSubjectX500Principal());
        }
    }

}
